package com.llh.uua.service

import com.llh.uua.model.SysRole
import com.llh.uua.model.SysRoles
import com.llh.uua.model.UserRoles
import org.ktorm.database.Database
import org.ktorm.dsl.*
import org.ktorm.entity.add
import org.ktorm.entity.filter
import org.ktorm.entity.find
import org.springframework.stereotype.Service

/**
 *
 *
 * Created At 2021/3/20 16:22
 * @author llh
 */
@Service
class RoleService(private val database: Database) :
    BaseService<SysRole, SysRoles>(database, SysRoles) {

    fun addRole(roleName: String) {
        val role = SysRole {
            this.roleName = roleName
        }
        sequence().add(role)
    }

    fun findByUserId(userId: Int): List<SysRole> {
        return database.from(SysRoles)
            .leftJoin(UserRoles, on = SysRoles.id eq UserRoles.roleId)
            .select(SysRoles.columns)
            .where { UserRoles.userId eq userId }
            .map { SysRoles.createEntity(it) }
    }

    fun findByRoleName(roleName: String): SysRole? {
        return sequence().find { it.roleName eq roleName }
    }
}